package com.ant.requestsecurity.interceptor;

import com.ant.requestsecurity.properties.CloudRequestSecurityProperties;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class ServerProtectInterceptor implements HandlerInterceptor {

    private CloudRequestSecurityProperties securityProperties;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,@NonNull Object handler) throws Exception {
        if(!securityProperties.getOnlyFetchByGateway()){
            return true;
        }

        String header = request.getHeader("Custom-Head");//请求头里的
        if(!ObjectUtils.isEmpty(header) && header.equals("I'm gateway request!")){
            return true;
        }else {
            //TODO 禁止访问，并跳转错误页面
            response.setStatus(403);
            log.info("=======请通过网关请求内部资源=======");
            return false;
        }
//        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    public void setSecurityProperties(CloudRequestSecurityProperties securityProperties){
        this.securityProperties = securityProperties;
    }
}
